//
//  CFKLineFullScreenViewController.m
//
//  Created by Zhimi on 2018/9/3.
//  Copyright © 2018年 hexuren. All rights reserved.
//

#import "LineKFullScreenViewController.h"
#import "Y_StockChartView.h"
#import "Y_KLineGroupModel.h"
#import "Y_KLineModel.h"
#import "Y_StockChartGlobalVariable.h"
#import "UIDevice+TFDevice.h"
@interface LineKFullScreenViewController ()<Y_StockChartViewDelegate,Y_StockChartViewDataSource,SRWebSocketDelegate>

@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet UILabel *nameLable;
@property (weak, nonatomic) IBOutlet UILabel *cnyPriceLable;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *changeLabel;


@property (strong, nonatomic) Y_StockChartView *lineKView;
@property (nonatomic, copy) NSString *type;
@property (nonatomic, assign) NSInteger currentIndex;
@property (nonatomic, strong) Y_KLineGroupModel *groupModel;
@property (nonatomic, assign) int klineRequestID;
@property (nonatomic, copy) NSMutableDictionary <NSString*, Y_KLineGroupModel*> *modelsDict;
@property (nonatomic, copy) NSString *timestr;
@property (nonatomic, copy) NSString *oldType;
@property (nonatomic, strong) NSMutableArray * dataArray; //币的详情信息
@property (nonatomic, strong) SRWebSocket *webSocket;
@end

@implementation LineKFullScreenViewController

+ (id)loadFromStoryboard{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    return [sb instantiateViewControllerWithIdentifier:@"LineKFullScreenViewController"];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
      [[UIApplication sharedApplication] setStatusBarHidden:YES];
   
    _lineKView.isFullScreen = YES;
     [self reconnect];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [self closeWebsoket];
}
- (void)closeWebsoket
{
    _webSocket.delegate = nil;
    [_webSocket close];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)reconnect
{
    [self.modelsDict removeAllObjects];
    _webSocket.delegate = nil;
    [_webSocket close];
    _webSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:WBSCOKETHOST_IP]];
    _webSocket.delegate = self;
    if (self.webSocket.readyState == SR_OPEN) {
        [self.webSocket sendPing:[EXUnit NSJSONSerializationWithmethod:@"server.ping" parameter:@[] id:1002]];
    }
    [_webSocket open];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self prefersStatusBarHidden];
    [self getHeadData:_modle];
    self.activityIndicatorView.tintColor = [UIColor whiteColor];
    self.activityIndicatorView.type = DGActivityIndicatorAnimationTypeBallSpinFadeLoader;
    self.bgView.backgroundColor =   self.view.backgroundColor = [UIColor backgroundColor];
    CAGradientLayer *layer = [CAGradientLayer layer];
    layer.startPoint = CGPointMake(0.5, 0);//（0，0）表示从左上角开始变化。默认值是(0.5,0.0)表示从x轴为中间，y为顶端的开始变化
    layer.endPoint = CGPointMake(0.5, 1);//（1，1）表示到右下角变化结束。默认值是(0.5,1.0)  表示从x轴为中间，y为低端的结束变化
    layer.colors = [NSArray arrayWithObjects:(id)ColorStr(@"#101624").CGColor,(id)ColorStr(@"#121826").CGColor,(id)ColorStr(@"#142030").CGColor,(id)ColorStr(@"#172236").CGColor, nil];
    layer.locations = @[@0.0f,@0.4f,@0.6f,@1.0f];//渐变颜色的区间分布，locations的数组长度和color一致，这个值一般不用管它，默认是nil，会平均分布
    layer.frame = self.bgView1.layer.bounds;
    [self.bgView1.layer insertSublayer:layer atIndex:0];
    
    self.currentIndex = -1;
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UpdateBPrice:) name:updateSymbolNotificationse object:nil];
    _lineKView = [[Y_StockChartView alloc] initWithFrame:CGRectMake(IS_IPHONE_X? 26:0, 50, UIScreenWidth - (IS_IPHONE_X? 26:0 ), UIScreenHeight  - 50 - (IS_IPHONE_X? 12:0 ))];
    _lineKView.isFullScreen = YES;
    _lineKView.itemModels = @[
                              [Y_StockChartViewItemModel itemModelWithTitle:Localized(@"hone_sharing") type:Y_StockChartcenterViewTypeKline],
                              [Y_StockChartViewItemModel itemModelWithTitle:[NSString stringWithFormat:@"1%@",Localized(@"hone_min")] type:Y_StockChartcenterViewTypeKline],
                              [Y_StockChartViewItemModel itemModelWithTitle:[NSString stringWithFormat:@"5%@",Localized(@"hone_min")] type:Y_StockChartcenterViewTypeKline],
                              [Y_StockChartViewItemModel itemModelWithTitle:[NSString stringWithFormat:@"15%@",Localized(@"hone_min")] type:Y_StockChartcenterViewTypeKline],
                              [Y_StockChartViewItemModel itemModelWithTitle:[NSString stringWithFormat:@"30%@",Localized(@"hone_min")] type:Y_StockChartcenterViewTypeKline],
                              [Y_StockChartViewItemModel itemModelWithTitle:Localized(@"hone_one_H_line") type:Y_StockChartcenterViewTypeKline],
                              [Y_StockChartViewItemModel itemModelWithTitle:Localized(@"hone_three_H_line") type:Y_StockChartcenterViewTypeKline],
                              [Y_StockChartViewItemModel itemModelWithTitle:Localized(@"hone_1_day_line") type:Y_StockChartcenterViewTypeKline],
                              [Y_StockChartViewItemModel itemModelWithTitle:Localized(@"hone_1_week_line") type:Y_StockChartcenterViewTypeKline],
                              [Y_StockChartViewItemModel itemModelWithTitle:Localized(@"hone_1_mon_line") type:Y_StockChartcenterViewTypeKline],
                              [Y_StockChartViewItemModel itemModelWithTitle:Localized(@"hone_index") type:Y_StockChartcenterViewTypeOther],
                              ];
    _lineKView.dataSource = self;
    _lineKView.delegate = self;
    _lineKView.backgroundColor = [UIColor backgroundColor];
    [self.view addSubview:_lineKView];
   
}
- (void)getHeadData:(HomeModle *)modle
{
    NSArray *titlearray = [modle.name componentsSeparatedByString:@"_"];
    int precision = modle.quote_asset_precision.intValue;
    self.nameLable.text = [NSString stringWithFormat:@" %@ / %@",titlearray[0],titlearray[1]];
   
    
    NSString * price = [NSString stringWithFormat:@"%@ ",[EXUnit formatternumber:precision assess:modle.last]];
    WeakSelf
    dispatch_async(dispatch_get_main_queue(), ^{
        
        
        if (modle.last.floatValue - modle.open.floatValue >=0) {
            weakSelf.priceLabel.textColor =ZHANGCOLOR;
            weakSelf.priceLabel.attributedText = [EXUnit getcontent:price image:@"k_zhang" index:price.length imageframe:CGRectMake(0, -2, 6, 16)];
            weakSelf.changeLabel.backgroundColor = ZHANGCOLOR;
        }else
        {
            weakSelf.priceLabel.textColor =DIEECOLOR;
            weakSelf.priceLabel.attributedText = [EXUnit getcontent:price image:@"k_dieline" index:price.length imageframe:CGRectMake(0, -2, 6, 16)];
            weakSelf.changeLabel.backgroundColor = DIEECOLOR;
        }
        float _x = modle.IncreaseDegree.floatValue;
        if (!isnan(_x)) {
            if (modle.last.floatValue - modle.open.floatValue >=0) {
                weakSelf.changeLabel.text = [NSString stringWithFormat:@"+ %.2f%%",modle.IncreaseDegree.floatValue];
            }else
            {
                weakSelf.changeLabel.text = [NSString stringWithFormat:@"%.2f%%",modle.IncreaseDegree.floatValue];
            }
        }else
        {
            weakSelf.changeLabel.text = @"0.00%";
        }
          weakSelf.cnyPriceLable.text = [EXUnit getPriceCurrencyWith:modle];
    });
}
- (IBAction)onClickCloseButton:(id)sender {
    if (self.onClickBackButton) {
        self.onClickBackButton(self);
    }
}

- (BOOL)prefersStatusBarHidden {
    return YES;//隐藏为YES，显示为NO
}

- (NSMutableDictionary<NSString *,Y_KLineGroupModel *> *)modelsDict {
    if (!_modelsDict) {
        _modelsDict = @{}.mutableCopy;
    }
    return _modelsDict;
}


- (void)reloadData {
    if (_groupModel) {
        [_dataArray removeAllObjects];
        [self showLoadingAnimation];
        NSInteger  endTime = [EXUnit getNowTimeTimestamp].integerValue; //就是当前时间
        float kCount;
        if ([self.type isEqualToString:@"1month"])
        {
            kCount = (UIScreenWidth -Y_StockChartKLinePriceViewWidth)/[Y_StockChartGlobalVariable kLineWidth];
        }else
        {
            kCount = (UIScreenWidth -Y_StockChartKLinePriceViewWidth)/0.4;
        }
        NSInteger  beginTime = endTime - (kCount*self.timestr.integerValue);  //开始时间
        
        NSArray * dataArray = @[_modle.name,@(beginTime),@(endTime),@(self.timestr.integerValue)];
        
        NSData *data = [EXUnit NSJSONSerializationWithmethod:@"kline.query" parameter:dataArray id:1020];
        [_webSocket send:data];    // 发送数据
        
    }
}

- (void)UpdateBPrice:(NSNotification *)message
{
    HomeModle * modle = message.object;
    if (modle.name ==_modle.name) {
        [self reloadPrice:modle];
    }
}
/*
 1546943400,
 0.01850662,
 0.01850786,
 0.01850786,
 0.01850662,
 52.7571,
 0.976389631848,
 EOS_ETH
 */
- (void)reloadPrice:(HomeModle *)modle
{
    _modle = modle;
    NSArray * ary = @[[EXUnit getNowTimeTimestamp],_modle.open,_modle.last,_modle.high,_modle.low,_modle.volume,_modle.name,@"0"];
    
    WeakSelf
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.groupModel != nil &&weakSelf.dataArray.count>0) {
            
            Y_KLineModel *lineModel = [self.groupModel.models lastObject];
            [lineModel initWithArray:ary];
            [self.lineKView.kLineView reDraw];
            
            [self getHeadData:modle];
        }
    });
    
}

#pragma mark - Y_StockChartViewDelegate

- (void)onClickFullScreenButtonWithTimeType:(Y_StockChartCenterViewType )timeType{
//    if (!_isShowKLineFullScreenViewController) {
//        [self showKLineFullScreenViewController];
//    }
}

#pragma mark - Y_StockChartViewDataSource

-(id)stockDatasWithIndex:(NSInteger)index {
    
    _oldType = self.type;
    switch (index) {
        case 0:
        {    self.type = @"1min";
            _timestr =@"60";
        }
            break;
        case 1:
            self.type = @"1min";
            _timestr =@"60";
            break;
        case 2:
            self.type = @"5min";
            _timestr =@"300";
            break;
        case 3:
            self.type = @"15min";
            _timestr =@"900";
            break;
        case 4:
            self.type = @"30min";
            _timestr =@"1800";
            break;
        case 5:
            self.type = @"1hour";
            _timestr =@"3600";
            break;
        case 6:
            self.type = @"4hour";
            _timestr =@"14400";
            break;
        case 7:
            self.type = @"1day";
            _timestr =@"86400";
            break;
        case 8:self.type = @"1week";
            _timestr =@"604800";
            break;
        case 9:self.type = @"1month";
            _timestr =@"2592000";
            break;
        default:
            break;
    }
    
    self.currentIndex = index;
    if (index == 0 || index == 1 || index == 2 || index == 3) {
        _lineKView.isMoreTimeDataUpdate = NO;
    }
    else{
        _lineKView.isMoreTimeDataUpdate = YES;
    }
    if(![self.modelsDict objectForKey:self.type]){
        if (![NSString isEmptyString:_oldType]) {
            [self.modelsDict removeObjectForKey:_oldType];
        }
        
        [self reloadData];
        
    }
    else{
        NSArray *array = [self.modelsDict objectForKey:self.type].models;
        
        return array;
    }
    
    return nil;
}

#pragma mark - SRWebSocketDelegate
///--------------------------------------
// 成功连接
- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
{
    NSInteger  endTime = [EXUnit getNowTimeTimestamp].integerValue; //就是当前时间
    NSLog(@"-->%f ---%d",[Y_StockChartGlobalVariable kLineWidth] ,Y_StockChartKLineMinWidth);
    float kCount = (UIScreenWidth -Y_StockChartKLinePriceViewWidth) / 0.5; //一行显示多少跟线
    NSInteger  beginTime = endTime - (kCount*_timestr.integerValue);  //开始时间
    NSArray * dataArray = @[_modle.name,@(beginTime),@(endTime),@(_timestr.integerValue)];
    NSData *data = [EXUnit NSJSONSerializationWithmethod:@"kline.query" parameter:dataArray id:1020];
    
    
    if (self.webSocket.readyState == SR_OPEN) {
        [_webSocket send:data];    // 发送数据
        
    }
    
}
// 断开连接
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
{
    _webSocket = nil;
}

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(nonnull NSString *)string
{
    NSLog(@"Received \"%@\"", string);
}
// 关闭连接
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;
{
    _webSocket = nil;
}

- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload;
{
    NSLog(@"WebSocket received pong");
}
// 接收消息
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {
    [self stopLoadingAnimation];
    //收到服务端发送过来的消息
    if ([NSString isEmptyString:message]) {
        return;
    }
    NSData *jsonData = [message dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *message1 = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves  error:nil];
    NSString * id =@"";
    if (![NSString isEmptyString:message1[@"id"]])
    {
        id = message1[@"id"];
    }
    if (id.integerValue ==1020) {
        if ([message1[@"result"] isEqual:[NSNull null]]) {
            [EXUnit showSVProgressHUD:@"暂时没有数据"];
            return;
        }
        NSArray * array = message1[@"result"];
        if (array.count>0)
        {
            self.dataArray = [NSMutableArray arrayWithArray:array];
            _groupModel = [Y_KLineGroupModel objectWithArray:_dataArray model:_modle];
            self.groupModel = _groupModel;
            [self.modelsDict setObject:_groupModel forKey:self.type];
            [self.lineKView reloadData];
            
            
        }
        
    }
    
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

@end
